package com.hd123.rumba.gwt.widget.client.grid;

import com.google.gwt.user.client.ui.Widget;
import com.hd123.rumba.gwt.widget.client.Util;
import com.hd123.rumba.gwt.widget.client.codenamebox.CodeNameBox;

public class CodeEditor extends CodeNameBox implements CellEditor {

  public CodeEditor() {
    super();
    getNameLabel().setVisible(false);
    setCellWidth(codeBox, "100%");
  }

  public void activate(DxGrid grid, int row, int col, String text, String width, String height,
      boolean readOnly) {
    setValue(text);
    super.setWidth(width);
    codeBox.setWidth("100%");
    super.setHeight("97%");
    setReadOnly(readOnly);
    grid.setWidget(row, col, this);
    setFocus(true);
  }

  public String getValue() {
    return getCode();
  }

  public boolean isLeftKeyToLeave() {
    return getCodeBox().isReadOnly() || getCodeBox().getCursorPos() == 0;
  }

  public boolean isRightKeyToLeave() {
    return getCodeBox().isReadOnly() || getValue() == null
        || getCodeBox().getCursorPos() == getValue().trim().length();
  }

  public void setFocus(boolean focused) {
    if (focused)
      Util.focusTextBox(getCodeBox());
    else
      getCodeBox().setFocus(focused);
  }

  public void setReadOnly(boolean readOnly) {
    getCodeBox().setReadOnly(readOnly);
    getSearchButton().setVisible(!readOnly);
    getCodeBox().setStyleName(readOnly ? "gwt-TextBox-Disabled" : "gwt-TextBox");
  }

  public void setValue(String value) {
    setCode(value);
  }

  // 不处理ENTER键
  public void onKeyDown(Widget sender, char keyCode, int modifiers) {
    if (sender == getCodeBox()) {
      if (keyCode == KEY_DOWN && (modifiers & MODIFIER_ALT) != 0 || keyCode == Util.KEY_DROPDOWN) {
        fireSearchStart(this);
      }
    }
  }
}
